/**
 * Copyright (C) © 2014 深圳市掌玩网络技术有限公司
 */

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 122.224.212.103
 */
public class UdpTransServer {
    static boolean isRunning = true;

    public static void main(String[] args) {
        DatagramSocket serverSocket = null;
        try {
            if (args == null || args.length < 3) {
                Log.i("Server", "监听的端口可以通过参数传入，分别是 本地监听端口、远程IP、远程端口");
                // return;
                args = new String[] { "1081", "0.0.0.0", "8888" };
            }
            // 获取本地监听端口、远程IP和远程端口
            int localPort = Integer.parseInt(args[0].trim());
            String remoteIp = args[1].trim();
            int remotePort = Integer.parseInt(args[2].trim());
            // 启动本地监听端口
            serverSocket = new DatagramSocket(localPort);
            Log.i("UDPTransServer", "localPort=" + localPort + ";remoteIp=" + remoteIp + ";remotePort=" + remotePort
                + ";启动本地监听端口" + localPort + "成功！");
            final UdpTranser transer = new UdpTranser(serverSocket);
            while (isRunning) {
                try {
                    // 获取客户端连接
                    byte[] buffer = new byte[10 * 1024];
                    DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
                    serverSocket.receive(incoming);
                    Log.i("accept one client", incoming.getSocketAddress());
                    transer.addSocket(incoming);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                // 建立连接远程
            }
        } catch (Exception e) {
            Log.e("tran", e);
        } finally {
            if (serverSocket != null) {
                serverSocket.close();
            }
        }
    }
}
